package com.generic.util;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.Random;

public class Encoder {
	private static int primeNum = 857;
	private static int subtractNum = 23;
	
	/**
	 * Encryption using MD5
	 * 
	 * @param Text to be encrypted
	 * @return The encrypted text
	 */
	public static String MD5(String text) {
		String md5Text = "";
		try {
			MessageDigest digest = MessageDigest.getInstance("MD5");
			md5Text = new BigInteger(1, digest.digest((text).getBytes())).toString(16);
		} catch (Exception e) {
			System.out.println("Error while calling MD5");
		}

		if (md5Text.length() == 31) {
			md5Text = "0" + md5Text;
		}

		return md5Text;
	}

	/**
	 * Encodes the given text
	 * 
	 * @param str Text to be encoded
	 * @return The encoded text
	 */
	public static String encode(String str) {
		String result = null;

		if (str != null) {
			StringBuffer sb = new StringBuffer();
			byte[] bytes = str.getBytes();

			for (int i = 0; i < bytes.length; i++) {
				sb.append((int)bytes[i] - subtractNum);
			}

			BigDecimal[] bd = new BigDecimal(sb.toString()).divideAndRemainder(new BigDecimal(primeNum));
			result = bd[0].toString() + "_" + bd[1].toString();
		}
		return result;
	}

	/**
	 * Decodes the given text
	 * 
	 * @param str Text to be decoded
	 * @return The decoded text
	 */
	public static String decode(String str) {
		String result = null;

		if (str != null) {
			String[] divide_remainder = str.split("_");
			String s = (new BigDecimal(divide_remainder[0]).multiply(new BigDecimal(primeNum)).add(new BigDecimal(divide_remainder[1]))).toString();
			
			byte[] bytes = new byte[s.length() / 2];
			int idx = 0;
			for (int i = 0; i < s.length(); i += 2) {
				int tmp = Integer.parseInt(s.substring(i, i + 2)) + subtractNum;
				bytes[idx] = Byte.valueOf(String.valueOf(tmp));
				idx++;
			}

			result = new String(bytes);
		}
		return result;
	}

	public static String getRandomCode(int codeLength) {
		byte[] bytes = new byte[codeLength];
		Random r = new Random();
		int hash = r.nextInt(26) + 65;
		for(int i=0; i<codeLength; i++) {
			bytes[i] = Byte.valueOf(String.valueOf(hash));
			hash = r.nextInt(26) + 65;
		}
		
		return new String(bytes);
	}
	
	public static void main(String[] args) {
		String s1 = "email@email.com";

		String enStr = Encoder.encode(s1);
		System.out.println("encode = " + enStr);
		String deStr = Encoder.decode(enStr);
		System.out.println("decode = " + deStr);
		String actStr = Encoder.getRandomCode(7);
		System.out.println("activation code = " + actStr);
	}
}
